package com.gitee.apecome.core.spring;

import com.gitee.apecome.core.annotation.ApeRpcService;
import com.gitee.apecome.core.remote.ApeRpcProviderFactory;
import com.gitee.apecome.core.remote.net.netty.server.NettyServer;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;
@Component
public class ApeRpcSpringProvider implements ApplicationContextAware, InitializingBean, DisposableBean {
    private Integer port;
    private Integer rpcServiceCount = 0;
    @Override
    public void destroy() throws Exception {
        
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        if (rpcServiceCount != 0) {
            System.out.println("server ===================");
            port = 7000; // 模拟 读取配置文件获取端口号
            NettyServer nettyServer = NettyServer.bulidServer(port);
            nettyServer.start();
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, Object> beansMap = applicationContext.getBeansWithAnnotation(ApeRpcService.class);
        for (Object bean : beansMap.values()) {
            if (bean.getClass().getInterfaces().length == 0) {
                throw new RuntimeException("it must inherit interface");
            }
            ApeRpcService annotation = bean.getClass().getAnnotation(ApeRpcService.class);
            String version = annotation.version();
            String beanName = bean.getClass().getInterfaces()[0].getName();
            ApeRpcProviderFactory.newInstance().addService(beanName, bean);
            rpcServiceCount++;
        }
    }
}
